import { CodecType, Uint8 } from "./codec";
import { make, type } from "./proto";
import { Frame, registerHandler } from "./recv";
import { serialPort } from "./SerialPort";

let globalSeq = 0;

function getSeq() {
    let seq = globalSeq;
    globalSeq ++;
    if (globalSeq > 255) {
        globalSeq = 0;
    }
    return seq;
}

function createPromise(timeout: number, type: number, seq: number) {
    return new Promise<Frame>((resolve, reject) => {
        let timeId = setTimeout(() => {
            reject('timeout');
        }, timeout);
        registerHandler((type << 8) + seq, (f) => {
            clearTimeout(timeId);
            resolve(f);
        });
    });
}

export async function simpleReq(cmd: number, args: CodecType[], rets: CodecType[]) {
    const seq = getSeq();
    const fut = createPromise(500, type.SIMPLE_RES, seq);
    await serialPort.write(make(type.SIMPLE_REQ, seq, [new Uint8(cmd), ...args]));
    const frame = await fut;
    frame.parse_res(rets);
}

export async function ping() {
    const seq = getSeq();
    const fut = createPromise(500, type.PONG, seq);
    await serialPort.write(make(type.PING, seq, []));
    await fut;
}


